<script setup>
import { ref, watch, computed } from 'vue';
import { getMySellAPI, getMyExchangeAPI ,getAddressAPI, sendAPI,refuseExchangeAPI,agreeExchangeAPI} from '@/api/Trade.js'; // 调整路径
import { useUserStore } from '@/stores/user';
import {ElMessage, ElMessageBox} from 'element-plus';
import { formatDate } from '@/utils/format.js';

const userStore = useUserStore();
const userId = userStore.UserId;
const activeTab = ref('trade'); // 默认选中商品订单
const tradeOrders = ref([]);
const exchangeOrders = ref([]);
const tradeStatusFilter = ref('');
const exchangeStatusFilter = ref('');
const addressList = ref([]);
const selectedAddressId = ref(null);
const showAddressDialog = ref(false);
const currentOrderId = ref(null);
const  currentNums = ref(null);
const currentGoodsId = ref(null);


// 状态映射
const tradeStatusMap = {
  0: '待付款',
  1: '已支付',
  2: '已取消',
  3: '已完成',
  4:'已发货'
};

const exchangeStatusMap = {
  0: '待确认',
  1: '已完成',
  2: '已取消',
  3: '已拒绝',
  4: '已发货'
};

// 获取商品订单
const fetchTradeOrders = async () => {
  try {
    const response = await getMySellAPI(userId);
    tradeOrders.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取商品订单失败');
  }
};

// 获取交换订单
const fetchExchangeOrders = async () => {
  try {
    const response = await getMyExchangeAPI(userId);
    exchangeOrders.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取交换订单失败');
  }
};

// 监听 activeTab 的变化，每次切换选项卡时请求数据
watch(activeTab, (newTab) => {
  if (newTab === 'trade') {
    fetchTradeOrders();
  } else if (newTab === 'exchange') {
    fetchExchangeOrders();
  }
});

// 筛选商品订单
const filteredTradeOrders = computed(() => {
  if (tradeStatusFilter.value === '') {
    return tradeOrders.value;
  }
  return tradeOrders.value.filter(order => order.status === parseInt(tradeStatusFilter.value));
});

// 筛选交换订单
const filteredExchangeOrders = computed(() => {
  if (exchangeStatusFilter.value === '') {
    return exchangeOrders.value;
  }
  return exchangeOrders.value.filter(order => order.status === parseInt(exchangeStatusFilter.value));
});
const fetchAddresses = async () => {
  try {
    const response = await getAddressAPI(userId);
    addressList.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取地址失败');
  }
};
const openAddressDialog = (orderId,nums, goodsId) => {
  console.log('openAddressDialog', orderId);
  currentOrderId.value = orderId;
 currentNums.value = nums;
  currentGoodsId.value = goodsId;
  fetchAddresses();
  showAddressDialog.value = true;
};
const confirmShipment = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择发件地址');
    return;
  }
  try {
    console.log(' currentOrderId' , currentOrderId.value);
    await sendAPI(currentOrderId.value, selectedAddressId.value ,currentGoodsId.value,currentNums.value);
    ElMessage.success('发货成功');
    showAddressDialog.value = false;
    await fetchTradeOrders(); // Refresh orders list
  } catch (error) {
    ElMessage.error('发货失败');
  }
};
// 拒绝交换函数，带确认弹窗
const refuseExchange = async (orderId) => {
  try {
    // 显示确认框
    await ElMessageBox.confirm(
        '确定要拒绝此交换订单吗？',
        '拒绝确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 用户确认后调用API
    await refuseExchangeAPI(orderId);
    ElMessage.success('拒绝交换成功');
    await fetchExchangeOrders(); // 刷新订单列表
  } catch (error) {
    // 用户取消或发生错误时的处理
    ElMessage.info('操作已取消');
  }
};

const openAgreeExchangeDialog = (orderId, nums, goodsId) => {
  currentOrderId.value = orderId;
  currentNums.value = nums;
  currentGoodsId.value = goodsId;
  fetchAddresses();
  showAddressDialog.value = true;
};
const confirmAgreeExchange = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择发件地址');
    return;
  }

  try {
    // 显示确认框
    await ElMessageBox.confirm(
        '确定要同意并发货此交换订单吗？',
        '确认发货',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 确认后调用API
    const data = {
      orderId: currentOrderId.value,
      goodsId: currentGoodsId.value,
      nums: currentNums.value,
      sellerAddressId: selectedAddressId.value,
      userId: userId
    };

    await agreeExchangeAPI(data);
    ElMessage.success('发货成功');
    showAddressDialog.value = false;
    await fetchExchangeOrders(); // 刷新交换订单列表
  } catch (error) {
    ElMessage.error('发货失败');
  }
};


// 页面加载时获取商品订单数据
fetchTradeOrders();
</script>

<template>
  <div class="manage-page">
    <!-- 将 el-tabs 包裹在一个固定位置的容器中 -->
    <div class="tabs-wrapper">
      <el-tabs v-model="activeTab" class="centered-tabs">
        <el-tab-pane name="trade" label="商品订单">
          <el-select v-model="tradeStatusFilter" placeholder="订单状态" style="margin-bottom: 10px; width: 200px;">
            <el-option value="" label="全部状态"/>
            <el-option value="0" label="待付款"/>
            <el-option value="1" label="已支付"/>
            <el-option value="2" label="已取消"/>
            <el-option value="3" label="已完成"/>
            <el-option value="4" label="已发货"/>
          </el-select>
          <el-table :data="filteredTradeOrders" class="centered-table">
            <el-table-column label="图片" width="100">
              <template #default="{ row }">
                <img :src="row.image" alt="商品图片" style="width: 100px; height: 100px;">
              </template>
            </el-table-column>
            <el-table-column label="订单编号" width="150">
              <template #default="{ row }">
                <p style="font-size: 12px">{{ row.orderNumber }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="120" />
            <el-table-column prop="nums" label="数量" width="65" />
            <el-table-column prop="price" label="价格/元"/>
            <el-table-column label="状态">
              <template #default="{ row }">
                <p>{{ tradeStatusMap[row.status] }}</p>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="120">
              <template #default="{ row }">
                <p style="font-size: 12px">{{formatDate(row.createTime)}}</p>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90">
              <template #default="{ row }">
                <el-button v-if="row.status === 1" type="primary" @click="openAddressDialog(row.id,row.nums,row.goodsId)">去发货
                </el-button>
                <el-button v-if="row.status === 0" type="danger">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane name="exchange" label="交换订单">
          <el-select v-model="exchangeStatusFilter" placeholder="订单状态" style="margin-bottom: 10px; width: 200px;">
            <el-option value="" label="全部状态"/>
            <el-option value="0" label="待确认"/>
            <el-option value="1" label="已完成"/>
            <el-option value="2" label="已取消"/>
            <el-option value="3" label="已拒绝"/>
            <el-option value="4" label="已发货"/>
          </el-select>
          <el-table :data="filteredExchangeOrders" class="centered-table" row-key="id">
            <el-table-column type="expand">
              <template #default="{ row }">
                <div>
                  <h4>交换商品列表</h4>
                  <el-table :data="row.exchangeGoodsList" style="margin-bottom: 20px;">
                    <el-table-column prop="image" label="图片">
                      <template #default="{ row }">
                        <img :src="row.image" alt="商品图片" style="width: 80px; height: 80px;">
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="商品名称" />
                    <el-table-column prop="price" label="价格/元" />
                    <el-table-column prop="exchangeGoodsNums" label="数量" />
                    <el-table-column prop="brokenRate" label="完整率" />
                    <el-table-column prop="description" label="描述" />
                  </el-table>
                  <h4>邮寄地址</h4>
                  <p>收件人：{{ row.mailAddress.addressee }}</p>
                  <p>电话：{{ row.mailAddress.addresseePhone }}</p>
                  <p>地址：{{ row.mailAddress.address }}</p>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="图片">
              <template #default="{ row }">
                <img :src="row.goodsImage" alt="商品图片" style="width: 100px; height: 100px;">
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称"/>
            <el-table-column label="订单编号" width="150">
              <template #default="{ row }">
                <p style="font-size: 12px">{{ row.orderNumber }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="goodsNum" label="交换数量" width="80" />
            <el-table-column label="状态" width="80">
              <template #default="{ row }">
                <p>{{ exchangeStatusMap[row.status] }}</p>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="120">
              <template #default="{ row }">
                <p style="font-size: 12px">{{formatDate(row.createTime)}}</p>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button v-if="row.status === 0" type="primary"
                           @click="openAgreeExchangeDialog(row.id, row.goodsNum, row.goodsId)">同意
                </el-button>
                <el-button v-if="row.status === 0" type="danger" @click="refuseExchange(row.id)">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <el-dialog v-model="showAddressDialog" title="选择发货地址">
    <div class="address-list">
      <div
          v-for="address in addressList"
          :key="address.id"
          @click="selectedAddressId = address.id"
          :class="['address-item', { selected: selectedAddressId === address.id }]"
      >
        <p>收件人：{{ address.addressee }}</p>
        <p>电话：{{ address.addresseePhone }}</p>
        <p>地址：{{ address.address }}</p>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="showAddressDialog = false">取消</el-button>
    <el-button type="primary" @click="confirmShipment" :disabled="!selectedAddressId">发货</el-button>
  </span>
  </el-dialog>


</template>

<style scoped>
.manage-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 20px;
  margin-left: -70%;
}

.tabs-wrapper {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 10;
  width: 100%;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.centered-tabs {
  width: 900px;
}

.centered-table {
  width: 900px;
  margin-top: 20px;
}
.address-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.address-item {
  border: 1px solid #eaeaea;
  border-radius: 5px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.address-item:hover {
  background-color: #f5f5f5;
}

.address-item.selected {
  border-color: #409eff;
  background-color: #e6f7ff;
}
</style>

